/**
 * 邀请码数据访问层
 */

const Logger = require('../utils/logger')

class InviteRepository {
  constructor(db) {
    this.db = db
    this.inviteCodesCollection = db.collection('invite_codes')
    this.inviteRecordsCollection = db.collection('invite_records')
    this._ = db.command
  }

  /**
   * 根据邀请码查询
   */
  async findByCode(code) {
    try {
      const result = await this.inviteCodesCollection.where({ code }).get()
      return result.data.length > 0 ? result.data[0] : null
    } catch (error) {
      Logger.error('InviteRepo', '查询邀请码失败', error)
      throw error
    }
  }

  /**
   * 创建邀请码
   */
  async createInviteCode(inviteData) {
    try {
      const result = await this.inviteCodesCollection.add({ data: inviteData })
      return result._id
    } catch (error) {
      Logger.error('InviteRepo', '创建邀请码失败', error)
      throw error
    }
  }

  /**
   * 更新邀请码使用次数
   */
  async incrementUsedCount(inviteCodeId) {
    try {
      await this.inviteCodesCollection.doc(inviteCodeId).update({
        data: {
          usedCount: this._.inc(1)
        }
      })
      return true
    } catch (error) {
      Logger.error('InviteRepo', '更新邀请码使用次数失败', error)
      throw error
    }
  }

  /**
   * 创建邀请记录
   */
  async createInviteRecord(recordData) {
    try {
      const result = await this.inviteRecordsCollection.add({ data: recordData })
      return result._id
    } catch (error) {
      Logger.error('InviteRepo', '创建邀请记录失败', error)
      throw error
    }
  }

  /**
   * 检查手机号是否已使用过邀请码
   */
  async hasUsedInviteCode(phone) {
    try {
      const result = await this.inviteRecordsCollection.where({ phone }).get()
      return result.data.length > 0
    } catch (error) {
      Logger.error('InviteRepo', '检查邀请码使用记录失败', error)
      throw error
    }
  }

  /**
   * 更新邀请码状态
   */
  async updateStatus(inviteCodeId, status) {
    try {
      await this.inviteCodesCollection.doc(inviteCodeId).update({
        data: { status }
      })
      return true
    } catch (error) {
      Logger.error('InviteRepo', '更新邀请码状态失败', error)
      throw error
    }
  }
}

module.exports = InviteRepository

